#include <stdio.h>
#include "defaultrunnable.h"

namespace unifysys {
	CDefaultRunnable::CDefaultRunnable(int threadNum)
	: _thread_num(threadNum)
	, _stop(false)
	, _thread(NULL)
	{}

	CDefaultRunnable::~CDefaultRunnable()
	{
		if (_thread != NULL)
		{
			delete[] _thread;
			_thread = NULL;
		}
	}

	void CDefaultRunnable::setThreadNum(int threadNum)
	{
		if (_thread != NULL)
		{
			return;
		}

		_thread_num = threadNum;
	}

	int CDefaultRunnable::start()
	{
		if (_thread != NULL || _thread_num < 1)
		{
			return -1;
		}

		_thread = new CThread[_thread_num];
		if (_thread == NULL)
		{
			return -2;
		}

		int i = 0;
		for (; i < _thread_num; ++i)
		{
			if (!_thread[i].start(this, (void *)((long)i)))
			{
				return i;
			}
		}

		return i;
	}

	void CDefaultRunnable::stop()
	{
		_stop = true;
	}

	void CDefaultRunnable::wait()
	{
		if (_thread != NULL)
		{
			for (int i = 0; i < _thread_num; ++i)
			{
				_thread[i].join();
			}
		}
	}

	void CDefaultRunnable::run(CThread* thread, void* arg)
	{
		long i = long(arg);
		printf("%s %s %d %ld\n", 
			__FILE__, __FUNCTION__, __LINE__, i);
	}
}